import json
import sys
import urllib.request
import urllib.error

def get_latest_release(owner, repo):
    url = f"https://api.github.com/repos/{owner}/{repo}/releases/latest"
    req = urllib.request.Request(url, headers={'User-Agent': 'PythonScript/1.0 (compatible with Python 3.6)'})
    try:
        with urllib.request.urlopen(req) as response:
            data = json.loads(response.read().decode())
            return data
    except urllib.error.HTTPError as e:
        if e.code == 404:
            print(f"❌ 仓库 {owner}/{repo} 不存在或没有发布任何 Release。")
        elif e.code == 403:
            print("⚠️ 请求被拒绝（请检查网络或 GitHub API 限制）")
        else:
            print(f"❌ HTTP 错误: {e.code}")
    except Exception as e:
        print(f"❌ 发生错误: {e}")
    return None

def main(repo_full):
    if len(sys.argv) != 2:
        print("用法: python get_github_release.py <owner/repo>")
        print("示例: python get_github_release.py microsoft/vscode")
        sys.exit(1)
    print(repo_full)
    if '/' not in repo_full:
        print("❌ 请使用格式: owner/repo")
        sys.exit(1)

    owner, repo = repo_full.split('/', 1)
    release = get_latest_release(owner, repo)

    if release:
        print("\n✅ 最新 Release 信息:")
        print(f"📦 标签 (Tag): {release['tag_name']}")
        print(f"📌 名称: {release.get('name', '无')}")
        print(f"📅 发布时间: {release['published_at']}")
        body = release.get('body') or '无'
        print(f"📝 说明:\n{body}\n")
        print("🔗 下载链接:")
        assets = release.get('assets', [])
        if assets:
            for asset in assets:
                print(asset["name"])
                print(asset['browser_download_url'])
                print(" ")
        else:
            print("  (无附件)")

